package com.shs.riggy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shs.riggy.common.CustomException;
import com.shs.riggy.entity.Category;
import com.shs.riggy.entity.Dish;
import com.shs.riggy.entity.Setmeal;
import com.shs.riggy.mapper.CategoryMapper;
import com.shs.riggy.service.CategoryService;
import com.shs.riggy.service.DishService;
import com.shs.riggy.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author 晚点再动心
 * @Date 2022/9/12
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;
    /**
     * 根据id删除分类，判断无删除之后再删除
     * @param id
     */
    @Override
    public void remove(Long id) {
        //1.查询当前分类是否关联了菜品，如果关联菜品则抛出一个异常

        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据getCategoryId这个字段进行查询匹配，看是否有关联
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);

        int count = dishService.count(dishLambdaQueryWrapper);
        if (count > 0){
            //此时代表有关联抛出一个异常
            throw  new CustomException("当前分类关联了菜品，不能删除！");
        }

        //2.查询当前分类是否关联了套餐，如果关联则抛出一个异常

        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        int count1 = setmealService.count(setmealLambdaQueryWrapper);
        if (count1 > 0){
            //有关联不能删除，抛出一个异常
            throw  new CustomException("当前分类关联了套餐，不能删除！");

        }

        //3.其余情况正常删除分类
        super.removeById(id);
    }
}


